<template>
  <el-dialog
    :title="!dataForm.id ? '新增' : '修改'"
    append-to-body
    :close-on-click-modal="false"
    @close="closeDialog()"
    :visible="visible"
    width="1000px"
  >
    <el-form
      :model="dataForm"
      :rules="dataRule"
      ref="dataForm"
      label-width="100px"
    >
      <el-row>
        <el-form-item label="优惠券名称" prop="couponName">
          <el-input v-model="dataForm.couponName" placeholder="请输入优惠券名称"
          ></el-input>
        </el-form-item>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="优惠券种类" prop="couponCate">
            <el-select
              v-model="dataForm.couponCate"
              filterable
              placeholder="请选择订单状态"
              clearable
              size="small"
              class="margin-left-xs"
              style="width:100%"
              :disabled="dataForm.id != null"
            >
              <el-option
                v-for="dict in couponCateList"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="类型:" prop="couponType">
            <el-radio-group v-model="dataForm.couponType" :disabled="dataForm.id != null" @change="handleCouponTypeChange">
              <el-radio label="1" border>代金券</el-radio>
              <el-radio label="2" border>折扣券</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="订单金额" prop="orderPrice">
            <el-tooltip class="item" effect="dark" content="订单金额（不包含运费）满多少可使用" placement="bottom">
              <el-input
                v-model="dataForm.orderPrice"
                placeholder="请输入订单金额"
                :disabled="dataForm.id != null"
              ></el-input>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <template v-if="dataForm.couponType == '1'">
            <el-form-item label="减免金额" prop="deductionPrice">
              <el-tooltip class="item" effect="dark" content="满足订单金额的基础上，减少的金额" placement="bottom">
                <el-input
                  v-model="dataForm.deductionPrice"
                  placeholder="请输入减免金额"
                  :disabled="dataForm.id != null"
                ></el-input>
              </el-tooltip>
            </el-form-item>
          </template>
          <template v-else-if="dataForm.couponType == '2'">
            <el-form-item label="折扣率" prop="discountRate">
              <el-tooltip class="item" effect="dark" content="折扣率范围0-10，9.5代表9.5折" placement="bottom">
                <el-input
                  v-model="dataForm.discountRate"
                  placeholder="请输入折扣率"
                  :disabled="dataForm.id != null"
                ></el-input>
              </el-tooltip>
            </el-form-item>
          </template>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="到期类型" prop="expirationType">
            <el-radio-group v-model="dataForm.expirationType" @change="handleExpirationTypeChange">
              <el-radio label="1" border>领券后生效</el-radio>
              <el-radio label="2" border>固定时间段</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <template v-if="dataForm.expirationType == '1'">
            <el-tooltip class="item" effect="dark" content="领券后在指定的天数内可以使用，超出则无法使用" placement="bottom">
              <el-form-item label="有效天数" prop="effectiveDays">
                <el-input
                  v-model="dataForm.effectiveDays"
                  placeholder="请输入有效天数"
                ></el-input>
              </el-form-item>
            </el-tooltip>
          </template>
          <template v-else-if="dataForm.expirationType == '2'">
            <el-form-item label="时间范围" prop="expirationDateRange">
              <el-tooltip class="item" effect="dark" content="在指定的时间区间内可以使用" placement="bottom">
                <el-date-picker
                  v-model="dataForm.expirationDateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  value-format="yyyy-MM-dd"
                  end-placeholder="结束日期">
                </el-date-picker>
              </el-tooltip>
            </el-form-item>
          </template>
        </el-col>
      </el-row>
      
      <el-row>
        <el-col :span="12">
          <el-form-item label="优惠券口令" prop="couponCode">
            <el-input
              v-model="dataForm.couponCode"
              placeholder="请输入优惠券口令"
            ></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="是否启用" prop="status">
            <el-radio-group v-model="dataForm.status">
              <el-radio label="1" border>启用</el-radio>
              <el-radio label="0" border>关闭</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="适用商品" prop="useGoodsType">
            <el-radio-group v-model="dataForm.useGoodsType" :disabled="dataForm.id != null">
              <el-radio label="1" border>全部商品</el-radio>
              <el-radio label="2" border>指定商品可用</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="排序" prop="orderBy">
            <el-input-number v-model="dataForm.orderBy" controls-position="right" :min="0" style="width:100%"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row>
        <el-col :span="12">
          <el-form-item label="积分" prop="point">
            <el-tooltip class="item" effect="dark" content="使用优惠券获得积分" placement="bottom">
              <el-input
                v-model="dataForm.point"
                placeholder="请输入积分"
                :disabled="dataForm.id != null"
              ></el-input>
            </el-tooltip>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          
        </el-col>
      </el-row>

      <el-row>
        <el-form-item label="规则说明" prop="remark">
          <el-input type="textarea" :rows="4" v-model="dataForm.remark" placeholder="请输入规则说明"></el-input>
        </el-form-item>
      </el-row>
      
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDialog">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()" v-if="canSubmit"
        >确定</el-button
      >
    </span>
  </el-dialog>
</template>

<script>
import { getObj, addObj, putObj } from "@/api/shop_operate/coupon";

export default {
  props:{
    visible: {
      type: Boolean,
      default: false
    },
  },
  data() {
    return {
      canSubmit: false,
      // 优惠券种类 1: 用户领取 2: 手动发放 3: 付费卷 4: 新人卷
      couponCateList: [
        {
          value: "1",
          label: "用户领取",
        },
        {
          value: "2",
          label: "手动发放",
        },
        {
          value: "3",
          label: "付费卷",
        },
        {
          value: "4",
          label: "新人卷",
        }
      ],
      dataForm: {
        id:null,
        couponType:'1',
        status:'1',
        expirationType:'1',
        useGoodsType:'1',
        discountRate:'',
        deductionPrice:'',
        effectiveDays:'',
        couponCate:'',
        // 时间范围
        expirationDateRange:[],
        point:0
      },
      dataRule: {
        couponName: [
          { required: true, message: "优惠券名称不能为空", trigger: "blur" },
        ],
        couponType: [
          { required: true, message: "优惠券类型不能为空", trigger: "blur" },
        ],
        couponCate: [
          { required: true, message: "优惠券种类不能为空", trigger: "blur" },
        ],
        orderPrice:[
          { required: true, message: "订单金额不能为空", trigger: "blur" },
        ],
        deductionPrice:[
          { required: true, message: "减免金额不能为空", trigger: "blur" },
        ],
        discountRate:[
          { required: true, message: "折扣率不能为空", trigger: "blur" },
        ],
        expirationType:[
          { required: true, message: "到期类型不能为空", trigger: "blur" },
        ],
        effectiveDays:[
          { required: true, message: "有效天数不能为空", trigger: "blur" },
        ],
        expirationDateRange:[
          { required: true, message: "时间范围不能为空", trigger: "blur" },
        ],
        status: [
          { required: true, message: "是否显示不能为空", trigger: "blur" },
        ],
        useGoodsType:[
          { required: true, message: "适用商品不能为空", trigger: "blur" },
        ],
        orderBy: [
          { required: true, message: "排序不能为空", trigger: "blur" },
        ],
        point: [
          { required: true, message: "积分不能为空", trigger: "blur" },
        ]
      },
    };
  },
  components: {
  },
  methods: {
    init(id) {
      this.canSubmit = true;
      if(id){
        getObj(id).then((response) => {
          this.dataForm = response.data.data;
          // 订单金额
          this.dataForm.orderPrice = (parseInt(this.dataForm.orderPrice / 100)).toString()
          // 减免金额
          this.dataForm.deductionPrice = this.dataForm.deductionPrice ? (parseInt(this.dataForm.deductionPrice) / 100).toString() : null
          // 折扣率
          this.dataForm.discountRate = this.dataForm.discountRate ? (this.dataForm.discountRate / 100).toString() : null
          // 格式化时间区间
          if(this.dataForm.effectiveStartDate && this.dataForm.effectiveEndDate){
            this.$set(this.dataForm, 'expirationDateRange', [])
            this.dataForm.expirationDateRange.push(this.dayjs(this.dataForm.effectiveStartDate).format('YYYY-MM-DD'))
            this.dataForm.expirationDateRange.push(this.dayjs(this.dataForm.effectiveEndDate).format('YYYY-MM-DD'))
            console.log(this.dataForm.expirationDateRange)
          }
        });
      }
      
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["dataForm"].validate((valid) => {
        if (valid) {
          this.canSubmit = false;
          let requestData = JSON.parse(JSON.stringify(this.dataForm))
          
          if(requestData.expirationDateRange && requestData.expirationDateRange.length > 0){
            requestData.effectiveStartDate = requestData.expirationDateRange[0] + " 00:00:00"
            requestData.effectiveEndDate = requestData.expirationDateRange[1] + " 23:59:59"
          }
          delete requestData.expirationDateRange
          // 订单金额转分
          requestData.orderPrice = requestData.orderPrice * 100
          // 减免金额转分
          requestData.deductionPrice = requestData.deductionPrice ? requestData.deductionPrice * 100 : null
          // 折扣率
          requestData.discountRate = requestData.discountRate ? requestData.discountRate * 100 : null
          if (requestData.id) {
            putObj(requestData)
              .then((data) => {
                this.$notify.success("修改成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          } else {
            addObj(requestData)
              .then((data) => {
                this.$notify.success("添加成功");
                this.$emit("refreshDataList");
                this.closeDialog()
              })
              .catch(() => {
                this.canSubmit = true;
              });
          }
        }
      });
    },
    //重置表单
    closeDialog() {
      this.$emit('update:visible', false)
    },

    /**
     * 切换优惠券类型
     */
    handleCouponTypeChange(){
      this.dataForm.deductionPrice = ''
      this.dataForm.discountRate = ''
    },

    /**
     * 切换到期类型
     */
    handleExpirationTypeChange(){
      this.dataForm.effectiveDays = ''
      this.dataForm.expirationDateRange = []
    }
  },
};
</script>
